import { Extension } from '@tiptap/core';
import jsPDF from 'jspdf';
import  '../../../SIMSUN-normal.js'
import html2canvas from 'html2canvas'
export const SaveContentExtension = Extension.create({
  name: 'saveContent',

  addCommands() {
    return {
      saveJSON:
        () =>
        ({ editor }) => {
          const content = editor.getJSON();
          const blob = new Blob([JSON.stringify(content, null, 2)], {
            type: 'application/json',
          });
          onDownload(blob, 'document.json');
          return true;
        },

      saveHTML:
        () =>
        ({ editor }) => {
          const content = editor.getHTML();
          const blob = new Blob([content], {
            type: 'text/html',
          });
          onDownload(blob, 'document.html');
          return true;
        },

      saveText:
        () =>
        ({ editor }) => {
          const content = editor.getText();
          const blob = new Blob([content], {
            type: 'text/plain',
          });
          onDownload(blob, 'document.txt');
          return true;
        },
  savePdf:
    () =>
    async ({ editor }) => {
      const editorEl = document.querySelector('.editor')
      if (!editorEl) {
        alert('未找到编辑器区域')
        return false
      }

      const canvas = await html2canvas(editorEl as HTMLElement, {
        scale: 2, // 提高分辨率
        useCORS: true // 若图片为跨域的，要保证服务端设置了 CORS header
      })

      const imgData = canvas.toDataURL('image/png')
      const pdf = new jsPDF({
        orientation: 'portrait',
        unit: 'mm',
        format: 'a4'
      })

      const imgProps = pdf.getImageProperties(imgData)
      const pdfWidth = pdf.internal.pageSize.getWidth()
      const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width

      pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight)

      const blob = pdf.output('blob')
      onDownload(blob, 'document.pdf')
      return true
    }
    };
  },
});

// 工具函数：处理下载逻辑
function onDownload(blob: Blob, filename: string) {
  const userFilename = prompt('Enter a filename:', filename);
  if (!userFilename) return;

  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = userFilename;
  a.click();
  URL.revokeObjectURL(url);
}
